<script setup lang="ts">
import { getOrg } from "@/api/settle";
import type { CascaderProps } from "element-plus";
import { ref, toRaw } from "vue";

defineOptions({ name: "OrgTreeSelect" });
defineProps<{ modelValue: string | undefined | null }>();
const emit = defineEmits<{
  (e: "update:modelValue", v: any): void;
  (e: "change", v: any): void;
}>();

type orgInfoItem = {
  organizationId: string;
  organizationName: string;
  children?: orgInfoItem[];
};
const list = ref<orgInfoItem[]>([]);

const getOrgs = async () => {
  const res = await getOrg({ allFlag: false });
  list.value = res.data;
  // 首次空值查询全部
  emit("change", null);
};
getOrgs();

const props: CascaderProps = {
  value: "organizationId",
  label: "organizationName",
  checkStrictly: true,
};

const _getNameByID = (list: orgInfoItem[], id: string): string | undefined => {
  let name;
  for (let i = 0, n = list.length; i < n; i++) {
    const current = list[i];
    if (current.organizationId === id) {
      name = current.organizationName;
      break;
    } else if (current.children) {
      name = _getNameByID(current.children, id);
      break;
    }
  }
  return name;
};
const getNameByID = (id: string) => {
  return _getNameByID(toRaw(list.value), id);
};
defineExpose({ getNameByID });
</script>

<template>
  <el-cascader
    :model-value="modelValue"
    :options="list"
    :props="props"
    :show-all-levels="false"
    clearable
    @change="$emit('change', $event?.at(-1))"
    @update:modelValue="$emit('update:modelValue', $event?.at(-1))"
  />
</template>

<style lang="scss" scoped></style>
